import matplotlib.pyplot as plt
import numpy as np
import json
import csv

centers = [
    (139382.3437, 146047.0951),
    (157688.4185, 148489.0310),
    (149441.1622, 167278.6394),
    (131764.7130, 162103.0925)
]

centers_x = [139382.3437, 157688.4185, 149441.1622, 131764.7130]
centers_y = [146047.0951, 148489.0310, 167278.6394, 162103.0925]

all_points = []
all_points_x = []
all_points_y = []

with open("points.txt", 'r') as f:
    lines = f.readlines()
    for line in lines:
        x, y = line.split(',')
        x, y = float(x), float(y)
        all_points.append((x, y))
        all_points_x.append(x)
        all_points_y.append(y)

data = json.load(open('out.temp'))
vs = data['fln']
vs.sort()

print len(vs)

vs_x = []
vs_y = []
for x, y in vs:
    vs_x.append(x)
    vs_y.append(y)


plan = []
with open('plan1.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        tmp = []
        for edge in row:
            a, b = edge[1:-1].split(',')[:2]
            a, b = int(a), int(b)
            tmp.append((a, b))
        plan.append(tmp)

fig = plt.figure(1)
fig.set_size_inches(18.5, 10.5)
plt.scatter(centers_x, centers_y, color='g')
plt.scatter(all_points_x, all_points_y)
plt.scatter(vs_x, vs_y, color='r')

def draw_circle(x, y, r=3000):
    theta = np.arange(0, 2* np.pi, 0.01)
    cx = x + r * np.cos(theta)
    cy = y + r * np.sin(theta)
    plt.plot(cx, cy)

def draw_line(v1, v2):
    k = (v1[1] - v2[1]) / (v1[0] - v2[0])
    xs = np.arange(v1[0], v2[0], 0.01)
    ys = v1[1] + k * (xs - v1[0])
    plt.plot(xs, ys)

for a, b in vs:
    draw_circle(a, b)

for i in range(8):
    for p in plan[:i + 1]:
        for x, y in p:
            for a, b in [(x, y), (y, x)]:
                va = vs[a] if a < len(vs) else centers[a - len(vs)]
                vb = vs[b] if b < len(vs) else centers[b - len(vs)]
                draw_line(va, vb)
    fig_name = "fig{}".format(i)
    plt.savefig(fig_name)
